package com.zzedu.framework.filer;

import com.zzedu.common.core.domain.AjaxResult;
import com.alibaba.fastjson.JSON;
import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.ServletRequest;
import jakarta.servlet.ServletResponse;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.GenericFilterBean;

import java.io.IOException;

/**
 * 处理负载均衡 探测器
 *  hk:Connection,value:close
 *  hk:Host,value:mng.bluetower.top
 *  hk:user-agent,value:clb-healthcheck
 */
@Component
public class HealthCheckFilter extends GenericFilterBean {
    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        HttpServletRequest httpServletRequest = (HttpServletRequest)request;
        String userAgent = String.valueOf(httpServletRequest.getHeader("user-agent"));
        if(userAgent.contains("clb-")||userAgent.contains("health")||userAgent.contains("check")){
            HttpServletResponse httpServletResponse = (HttpServletResponse)response;
            httpServletResponse.setStatus(HttpStatus.OK.value());
            httpServletResponse.getWriter().println(JSON.toJSONString(AjaxResult.error("服务健康")));
            httpServletResponse.getWriter().flush();
        }else{
            chain.doFilter(request,response);
        }
    }
}
